# Create your views here.
# 一般这三个经常用的，所以最好是包含进来
from django.shortcuts import render,HttpResponse,redirect
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
from app01 import models




from pymongo import MongoClient
# 实例化client ,建立连接(说明：如果是本机，其实不需要传参数也行)
client = MongoClient(host='127.0.0.1', port=27017)
def videos(request):
    # 从mongodb中获取数据
    collection = client['myspider']['itcast']
    cnt=collection.find().count()
    type=request.GET.get('type')
    if type is None or type=='全部':
        # 获取所有视频
        video_list=collection.find()
    else:
        video_list=collection.find({"url_name":type})
    # 获取分类列表
    videocg_list=collection.distinct("url_name")
    videocg_list1 = videocg_list[:8]
    videocg_list2 = videocg_list[8:16]
    videocg_list3 = videocg_list[16:]
    print(video_list)
    # return HttpResponse(cnt)
    return render(request, "app01/video.html",{"video_list":video_list,"videocg_list1":videocg_list1,"videocg_list2":videocg_list2,
                                               "videocg_list3": videocg_list3})


 # "_id" : ObjectId("5d21df6d08c68b0113dca904"),
 # "video_url" : "http://v.itheima.com/python/聚类算法/00_00_人工智能课程简介.mp4",
 # "download_latency" : 83.64478421211243,
 # "download_timeout" : 180,
 # "depth" : 2,
 # "course_name" : "【Python+人工智能】Python|360°解读机器学习经典算法",
 # "url" : "http://yun.itheima.com/course/c27.html",
 # "url_name" : "Python+人工智能",
 # "course_img" : "http://yun.itheima.com/Upload/./Images/20190219/5c6b58c76438a.jpg",
 # "download_slot" : "yun.itheima.com",
 # "course_url" : "http://yun.itheima.com/course/525.html",
 # "course_looks" : "2918人学习"


# 视频详情
def videoinfo(request):
    video_url=request.GET.get('a')
    print("video_url",video_url)
    return render(request,"app01/videoinfo.html",{"video_url":video_url})

from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
class MyAuth(BaseAuthentication):
    def authenticate(self,request):
        token=request.GET.get('token')
        if not token:
            raise exceptions.APIException('用户认证失败')
        return ("alex",1234)

    def authenticate_hear(self,val):
        pass

#from django.views import  View
from rest_framework.views import APIView
from videosite import tasks
class TestView(APIView):
    # throttle_classes = [MyAuth,]

    def get(self,request,*args,**kwargs):
        # return HttpResponse(str(request.user)+str(request.auth))
        print("start running task",tasks.a)
        res = tasks.add.delay(228, 24)
        print("async task res", res.get())
        return HttpResponse('res {0}'.format(res.get()))
